/**
 * Created by shudong.msd(风骐) on 2016/4/17.
 */
app.directive('deleteConfirm',function(){

    var comutil = new commUtils();

    function syncData(scope,targetId,type){

        if(type=='all'){
            for(var i in scope.allFinishMission.list){
                if(scope.allFinishMission.list[i].id==targetId){
                    scope.allFinishMission.list.splice(i,1);
                    scope.allFinishMission.count -=1;
                    scope.allFinishMission.currentRecords -=1;
                    break;
                }
            }
        }else if(type=='unread'){
            for(var j in scope.unReadMission.list){
                if(scope.unReadMission.list[j].id==targetId){
                    scope.unReadMission.list.splice(j,1);
                    scope.unReadMission.count -= 1;
                    scope.unReadMission.currentRecords -= 1;
                    break;
                }
            }
        }

        scope.$emit('delete_mission', {'id':targetId,'type':type});

    }

    return{
        restrict:'A',
        controller:function($scope,$http,$state){
            $scope.deleteMission = function(targetId){
                $http.post(UrlMappings.DELETE_MISSION+targetId,null,{
                    params : {
                        'access_token':comutil.getTocken()
                    },
                    headers:{
                        'Accept':'application/json',
                        'Content-Type':'application/x-www-form-urlencoded'
                    }
                }).success(function(data){
                    if(!data){
                        alert('删除失败');
                    }
                    /*if(!scope.$$phase){
                        scope.$apply();
                    }*/
                }).error(function(data,status){
                    if(status=='401')comutil.logout($state);
                });

            }
        },
        link:function(scope,ele,attr){
            ele.confirm({
                text: "你确定要删除此任务吗？",
                confirm: function(button) {
                    var targetId = attr.deleteConfirm;
                    var type = attr.missionType;
                    scope.deleteMission(targetId);

                    syncData(scope,targetId,type);

                },
                cancel: function(button) {
                    // nothing to do
                },
                confirmButton: "确定",
                cancelButton: "取消",
                post: false,
                confirmButtonClass: "mz-ok-btn",
                cancelButtonClass: "mz-no-btn",
                dialogClass: "mz-dialog"
            });
        }
    };
});

